import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.cj.jdbc.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
class Message{
    public String from;
    public String to;
    public String message;
    private Timestamp postTime;

    public String getPostTime() {
        // 此处需要把这个时间戳, 转成格式化时间.
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        return format.format(postTime);
    }

    public void setPostTime(Timestamp postTime) {
        this.postTime = postTime;
    }

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                ", postTime=" + postTime +
                '}';
    }
}
@WebServlet("/message")
public class MessageWall extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private static String jdbcUrl = "jdbc:mysql://localhost:3306/message_db?allowPublicKeyRetrieval=true&characterEncoding=utf8&useSSL=false";
    private static String username = "username";
    private static String password = "password";
    @Override  //存档
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);//idea快速生成变量名快捷键:Ctrl+Alt+V
        //把消息临时保存到内存里面，一旦重启服务器，内存数据就没了，科学的应该是保存的数据库里面。
        try {
            save(message);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.setStatus(200);
        resp.getWriter().write("ok");
    }
    @Override //读档
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");//setContentType 这设置的是一个属性呀
        List<Message> messageList = null;
        try {
            messageList = load();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String respJson = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respJson);

    }
    //使用JDBC存储数据
    private void save(Message message) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl(jdbcUrl);
        ((MysqlDataSource)dataSource).setUser(username);
        ((MysqlDataSource)dataSource).setPassword(password);
        //2,建立连接
        Connection connection = dataSource.getConnection();
        //构造sql语句
        String sql= "insert into message values(?,?,?,now());";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,message.from);
        statement.setString(2,message.to);
        statement.setString(3,message.message);
        //执行sql语句
        statement.executeUpdate();//bug在这里，写错函数了
        //释放资源，关闭连接
        statement.close();;
        connection.close();
    }
    //使用JDBC加载数据
    private List<Message> load() throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl(jdbcUrl);
        ((MysqlDataSource)dataSource).setUser(username);
        ((MysqlDataSource)dataSource).setPassword(password);
        //2,建立连接
        Connection connection = dataSource.getConnection();
        //构造sql语句
        String sql= "select * from message;";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        List<Message> messageList = new ArrayList<>();
        while (resultSet.next()){
            Message message=new Message();
            message.from=resultSet.getString("from");
            message.to=resultSet.getString("to");
            message.message=resultSet.getString("message");
            message.setPostTime(resultSet.getTimestamp("date"));
            messageList.add(message);
        }
        resultSet.close();
        connection.close();
        return messageList;
    }
}
